package com.tuomaxu.utils;

import com.tuomaxu.servlet.HttpServlet;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WebXmlParseUtil {

    public static Map<String, HttpServlet> parse(File file) throws FileNotFoundException {
        Map<String, HttpServlet> map = new HashMap<>();
        InputStream resourceAsStream = new FileInputStream(file);
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            //获取所有servlet元素
            List<Node> servletElements = rootElement.selectNodes("//servlet");
            for (Node servletElement : servletElements) {
                //获取当前servlet标签的name
                String servletName = servletElement.selectSingleNode("servlet-name").getStringValue();
                //通过名字找到对应的servletMapping标签
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                //获取该名字对应的url
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                //获取该servlet的处理类
                String servletClass = servletElement.selectSingleNode("servlet-class").getStringValue();
                //实例话servlet类并以url为可以存入map中
                map.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }
}
